import { routerRedux } from 'dva/router';
import { withLoading } from 'utils/dva';
import { breadProvider } from 'utils/bread';
import services from '../services';
import model from './model';

export default model.extend({
    namespace: 'layout',
    state: {
      openKeys: JSON.parse(window.localStorage.getItem('openKeys')) || [],
      user: JSON.parse(window.localStorage.getItem('user')) || {},
      loading: {
        login: false
      },
      bread: {
        pathArray: [],
        paramMap: {}
      },
      captcha: '',
      siderFoldN: false
    },

    subscriptions: {
      setup({ dispatch, history }) {
        // 监听路由的变化，请求页面数据
        return history.listen(({ pathname }) => {
          dispatch({
            type: 'updateBread',
            payload: {
              pathname
            }
          });
        });
      }
    },

    effects: {
      * login({ payload }, { put, call, update }) {
        const user = yield call(withLoading(services.api.login, 'login'), { ...payload });
        if(user.status === 'SUCCESS') {
          yield update({ user: user.data || {} });
          window.localStorage.setItem('user', JSON.stringify(user.data));
          yield put(routerRedux.push('/user/userManage'));
        }
      },
      * logout({ payload }, { call, put, update }) {
        yield call(withLoading(services.api.logout), { ...payload });
        yield update({ user: payload });
        yield put(routerRedux.push('/login'));
      },
      * getCaptcha({ payload }, { call, update }){
        const { data: captcha } = yield call(withLoading(services.user.getCaptcha), { ...payload });
        yield update({ captcha });
      }
    },

    reducers: {
      handleNavOpenKeys(state, { payload: openKeys }) {
        return {
          ...state,
          ...openKeys
        };
      },
      updateBread(state, { payload }) {
        return {
          ...state,
          bread: breadProvider.getBread(payload.pathname)
        };
      },
      switchSider(state, { payload }){
        return {
          ...state,
          siderFoldN: !state.siderFoldN
        };
      }
    }
  });
  